package cn.yj.netty.server;

import cn.yj.netty.annotation.EnableNettyServer;
import cn.yj.netty.message.convert.IProtocolMessageConvert;
import cn.yj.netty.support.test.NettyServer;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.MultiValueMap;

import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author 永健
 * @since 2022-01-17 16:55
 */
public class NettyServerAutoConfig implements ImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {

        Set<String> annotationTypes = annotationMetadata.getAnnotationTypes();
        Iterator zClasses = annotationTypes.iterator();
        Class<? extends IProtocolMessageConvert> messageClass = null;
        Class<? extends INettyServer> nettyServerClass = null;
        while (zClasses.hasNext()) {
            String type = (String) zClasses.next();
            if (type.equals(EnableNettyServer.class.getName())) {
                MultiValueMap<String, Object> allAnnotationAttributes =
                        annotationMetadata.getAllAnnotationAttributes(EnableNettyServer.class.getName());
                // netty端口
                List<Object> port = allAnnotationAttributes.get("port");

                // 消息处理类
                messageClass = (Class<? extends IProtocolMessageConvert>) allAnnotationAttributes.get(
                        "protocolCovertClass").get(0);

                // netty服务类
                nettyServerClass = (Class<? extends INettyServer>) allAnnotationAttributes.get("server").get(0);

                Object portV = port.get(0);

                if (portV == null) {
                    throw new RuntimeException("启动netty服务,请填写端口");
                }
                NettyServer.setSocketAddress(new InetSocketAddress(Integer.parseInt(portV.toString())));
            }
        }
        return new String[]{nettyServerClass.getName(), messageClass.getName()};
    }
}
